/**
 * Created by Administrator on 2018-04-16.
 */
odoo.define('account_extend.NotifyWidget', function (require) {
    "use strict";

    var ReconciliationModel = require('account.ReconciliationModel');
    var ReconciliationRenderer = require('account.ReconciliationRenderer').ManualLineRenderer;
    var ControlPanelMixin = require('web.ControlPanelMixin');
    var Widget = require('web.Widget');
    var core = require('web.core');
    var ReconciliationClientAction = require('account.ReconciliationClientAction');
    var framework = require('web.framework');
    var AbstractWebClient = require('web.AbstractWebClient');
    var Tree = require('web.ListView');
    var TreeController = require('web.ListController');
    var qweb = core.qweb;

    function Notify(parent, action) {
        return new AbstractWebClient(parent, action).do_notify(action.params.title, action.params.message, action.params.sticky, action.params.className);
    }

    function Warning(parent, action) {
        return new AbstractWebClient(parent, action).do_warn(action.params.title, action.params.message, action.params.sticky, action.params.className);
    }

    core.action_registry.add('notify', Notify);
    core.action_registry.add('warning', Warning);

    ReconciliationRenderer.include({
        events: _.extend({}, ReconciliationRenderer.prototype.events, {
            'click #select_all': '_select_all',
            'click .invoice_line td input': '_show_amount_input',
            'change .invoice_line td.cell_left span input': '_change_amount',
        }),
        update: function (state) {
            var self = this;
            this._super.apply(this, arguments);
            var props = _.filter(state.reconciliation_proposition, {'display': true});
            // if (props.length) {
            //     var $props_root = this.$('.accounting_view tbody');
            //     var $select_all = $('<tr><td class=""><input type="checkbox" id="select_all"/></td><td class="">全选</td><td class="cell_due_date"></td><td class="cell_label"></td><td id="invoice_total_amount" class="cell_left"></td><td class="cell_right"></td><td></td></tr>');
            //     $props_root.prepend($select_all);
            //     _.each(props, function (line) {
            //         self.model._rpc({
            //             model: 'account.move.line',
            //             // method: 'get_invoice_by_name',
            //             args: [line.id],
            //         }).then(function (result) {
            //             var $props = self.$('.accounting_view tbody tr[data-line-id=' + line.id + ']');
            //             var invoice_line = result[line.id];
            //             if (invoice_line && invoice_line.length > 0 && $props) {
            //                 var $invoice_line = $(qweb.render("account_extend.AccountAccountLine", {'lines': invoice_line, 'move_id': line.id}));
            //                 $props.after($invoice_line);
            //             }
            //         });
            //     });
            // }
        },

        _change_amount: function () {
            var self = this;
            var $invoic_lines = this.$('.invoice_line .cell_head input');

            var total_amount = 0.000;
            for (var i=0; i < $invoic_lines.length; i++){
                if (!$invoic_lines[i].disabled && $invoic_lines[i].checked){
                    var $invoic_lines_value = this.$('.invoice_line .cell_left span input[data-id="' + $invoic_lines[i].value + '"]');
                    total_amount += parseFloat($invoic_lines_value.val());
                }

            }
            var html_text = '';
            if (total_amount){
                html_text = '总金额: ' + total_amount + '¥';
            }
            this.$('#invoice_total_amount').html(html_text)
        },

        _select_all: function (env) {
            var self = this;
            var root_checked = env.target.checked;
            var $invoic_lines = this.$('.invoice_line .cell_head input');
            for (var i=0; i < $invoic_lines.length; i ++){
                if (!$invoic_lines[i].disabled){
                    $invoic_lines[i].checked = root_checked && true || false;
                    var line_id = $invoic_lines[i].value;
                    var $invoic_inputs = this.$('.invoice_line[data-line-id="'+ line_id+'"] .cell_left');
                    if (root_checked) {
                        $invoic_inputs.children().show();
                    } else {
                        $invoic_inputs.children().hide();
                    }
                }

            }
            self._change_amount();
        },

        _show_amount_input: function (env) {
            var self = this;
            var checked = env.target.checked;
            var value = env.target.value;
            var $invoic_inputs = this.$('.invoice_line[data-line-id="'+ value +'"] .cell_left');
            if (checked) {
                $invoic_inputs.children().show();
            } else {
                $invoic_inputs.children().hide();
            }
            self._change_amount();
        },

        _onValidate: function () {
            var self = this;
            var $invoic_lines = this.$('.invoice_line .cell_head input');
            var checked_lines = _.filter($invoic_lines, {'checked': true});
            var invoice_info = {};
            if (checked_lines.length <= 0){
                checked_lines = $invoic_lines;
            }
            for (var i=0; i < checked_lines.length; i++){
                var invoice_id = checked_lines[i].value;
                var move_id = checked_lines[i].getAttribute('move-id');
                var amount = this.$('.cell_left span input[data-id="' + invoice_id + '"]').val();
                if (move_id in invoice_info){
                    invoice_info[move_id].push(
                        {
                            id: invoice_id,
                            validate_amount: amount,
                            move_id: move_id
                        }
                    )
                } else {
                    invoice_info[move_id] = [{
                        id: invoice_id,
                        validate_amount: amount,
                        move_id: move_id
                    }];
                }
            }
            this.model.invoice_line_info = invoice_info;
            this.trigger_up('validate');
        }
    });

    // ReconciliationClientAction.ManualAction.include({});
    ReconciliationModel.ManualModel.include({
        init: function (parent, options) {
            this._super.apply(this, arguments);
            this.invoice_line_info = {};
        },
        validate: function (handle) {
            var self = this;
            var handles = [];
            if (handle) {
                handles = [handle];
            } else {
                _.each(this.lines, function (line, handle) {
                    if (!line.reconciled && !line.balance.amount && line.reconciliation_proposition.length) {
                        handles.push(handle);
                    }
                });
            }

            var def = $.when();
            var process_reconciliations = [];
            var reconciled = [];
            _.each(handles, function (handle) {
                var line = self.getLine(handle);
                if (line.reconciled) {
                    return;
                }
                var props = line.reconciliation_proposition;
                if (!props.length) {
                    self.valuenow++;
                    reconciled.push(handle);
                    line.reconciled = true;
                    process_reconciliations.push({
                        id: line.type === 'accounts' ? line.account_id : line.partner_id,
                        type: line.type,
                        mv_line_ids: [],
                        new_mv_line_dicts: [],
                    });
                } else {
                    var mv_line_ids = _.pluck(_.filter(props, function (prop) {
                        return !isNaN(prop.id);
                    }), 'id');
                    var new_mv_line_dicts = _.map(_.filter(props, function (prop) {
                        return isNaN(prop.id);
                    }), self._formatToProcessReconciliation.bind(self, line));
                    process_reconciliations.push({
                        id: null,
                        type: null,
                        mv_line_ids: mv_line_ids,
                        new_mv_line_dicts: new_mv_line_dicts
                    });
                }
                line.reconciliation_proposition = [];
            });

            if (process_reconciliations.length) {
                def = self._rpc({
                    model: 'account.move.line',
                    method: 'process_reconciliations',
                    args: [process_reconciliations],
                    context: {
                        invoice_info: self.invoice_line_info
                    }
                });
            }

            return def.then(function () {
                var defs = [];
                var account_ids = [];
                var partner_ids = [];
                _.each(handles, function (handle) {
                    var line = self.getLine(handle);
                    if (line.reconciled) {
                        return;
                    }
                    line.filter = "";
                    line.offset = 0;
                    defs.push(self._performMoveLine(handle).then(function () {
                        if (!line.mv_lines.length) {
                            self.valuenow++;
                            reconciled.push(handle);
                            line.reconciled = true;
                            if (line.type === 'accounts') {
                                account_ids.push(line.account_id.id);
                            } else {
                                partner_ids.push(line.partner_id.id);
                            }
                        }
                    }));
                });
                return $.when.apply($, defs).then(function () {
                    if (account_ids.length) {
                        self._rpc({
                            model: 'account.account',
                            method: 'mark_as_reconciled',
                            args: [account_ids],
                        });
                    }
                    if (partner_ids.length) {
                        self._rpc({
                            model: 'res.partner',
                            method: 'mark_as_reconciled',
                            args: [partner_ids],
                        });
                    }
                    return {reconciled: reconciled, updated: _.difference(handles, reconciled)};
                });
            });
        },
    });

    var new_TreeController = TreeController.extend({
        renderButtons: function ($node) {
            var self = this;
            this._super.apply(this, arguments);
            var $button_auto = $('<button accesskey="s" class="btn btn-primary btn-sm o_form_button_save" type="button" id="button_auto">自动核销</button > ');
            var $button_hand = $('<button accesskey="s" class="btn btn-primary btn-sm o_form_button_save" type="button" id="button_hand">手动核销</button >');
            this.$buttons.append($button_auto);
            this.$buttons.append($button_hand);
        }
    });

    var new_Tree = Tree.extend({
        config: _.extend({}, Tree.prototype.config, {
            Controller: new_TreeController,
        }),
    });
    var view_registry = require('web.view_registry');

    view_registry.add('tree_charge_off', new_Tree);
});